import axios from 'axios'
import { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError, AxiosHeaders } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user'
import router from '@/router'

interface ResponseData {
  code: number
  msg?: string
  error?: string
  message?: string
}
class HttpRequest {
  instance: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    // 创建axios实例
    this.instance = axios.create(config)
    // 添加请求拦截
    this.instance.interceptors.request.use(
      // 发送请求前执行
      (config: AxiosRequestConfig) => {
        const userStore = useUserStore()
        const token = userStore.token
        token && (config.headers as AxiosHeaders).set('Authorization', `Bearer ${token}`)
        return config
      },
      // 请求错误执行
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )
    // 添加响应拦截
    this.instance.interceptors.response.use(
      // 响应完成执行
      (response: AxiosResponse) => {
        const data: ResponseData = response.data
        if (data.code !== 0) {
          ElMessage.error(data.error || data.message || data.msg || '请求错误!')
        }
        return response.data
      },
      // 响应错误执行
      (error: AxiosError) => {
        const { response } = error
        if (response) {
          this.errorHandle(response.status, response.data as ResponseData | null)
          return response.data
        }
        ElMessage.error(error.message)
      }
    )
  }
  errorHandle(status: number, data: ResponseData | null) {
    const msg = data?.error || data?.message || data?.msg
    if (msg && status !== 401) {
      ElMessage.error(msg)
      return
    }
    switch (status) {
      case 400:
        ElMessage.error('请求错误!')
        break
      case 401:
        ElMessageBox.confirm('登陆状态已过期，请重新登录', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const userStore = useUserStore()
          userStore.logout(router.currentRoute.value.fullPath)
        })
        break
      case 403:
        ElMessage.error('权限不足，拒绝访问!')
        break
      case 404:
        ElMessage.error('请求的资源不存在!')
        break
      case 500:
        ElMessage.error('服务器内部错误，无法完成请求!')
        break
      case 501:
        ElMessage.error('服务器不支持请求的功能，无法完成请求!')
        break
      case 502:
        ElMessage.error('Bad Gateway!')
        break
      default:
        ElMessage.error(`连接错误${status}`)
        break
    }
  }
}

export default HttpRequest
